//文章详情页

<template>
    <div class="article-detail-container">
      <el-button type="info" @click="goBack" class="back-button">返回文章列表</el-button>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="article">
        <h2 class="article-title">{{ article.title }}</h2>
        <p class="article-meta">
          <span class="author">作者: {{ article.authorName || '匿名用户' }}</span>
          <span class="time">发布时间: {{ formatTime(article.addedTime) }}</span>
        </p>
        <div class="article-body">
          <p>{{ article.body }}</p>
        </div>
        <div class="article-details">
          <span v-if="article.userid" class="detail-item">用户ID: {{ article.userid }}</span>
          <span v-if="article.categoryid" class="detail-item">分类ID: {{ article.categoryid }}</span>
          <span v-if="article.completed !== null" class="detail-item">状态: {{ article.completed ? '已完成' : '未完成' }}</span>
        </div>

        <!-- 评论区 -->
        <div class="comments-section">
          <h3>发表评论</h3>
          <el-input
            v-model="commentBody"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评论..."
            class="comment-textarea"
          />
          <el-button type="primary" @click="submitComment" class="submit-comment-button">提交评论</el-button>

          <h3 class="comments-list-title">评论列表 ({{ comments.length }})</h3>
          <div v-if="commentsLoading" class="loading">评论加载中...</div>
          <div v-else-if="commentsError" class="error">{{ commentsError }}</div>
          <div v-else-if="comments.length > 0" class="comments-list">
            <div v-for="(comment, index) in comments" :key="comment.id" class="comment-card">
              <div class="comment-header">
                <span class="comment-author">{{ comment.authorName || '匿名用户' }} (ID: {{ comment.userid }})</span>
                <span class="comment-time">{{ formatTime(comment.addedTime) }}</span>
              </div>
              <p class="comment-body">{{ comment.body }}</p>
              <span class="comment-index">第 {{ index + 1 }} 条评论</span>
            </div>
          </div>
          <div v-else class="no-comments">暂无评论。</div>
        </div>

      </div>
      <div v-else class="no-article">未找到该文章。</div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/stores/user'; // 导入 userStore
  import { ElMessage } from 'element-plus'; // 导入 ElMessage 用于提示

  interface Article {
    id: number;
    title: string;
    body: string | null;
    addedTime: string;
    userid: number | null;
    completed: boolean | null;
    categoryid: number | null;
    authorName: string | null;
  }

  interface Comment {
    id: number;
    body: string;
    addedTime: string;
    userid: number;
    replyType: string;
    articleid: number;
    authorName: string;
  }
  
  const route = useRoute();
  const router = useRouter();
  const article = ref<Article | null>(null);
  const loading = ref(true);
  const error = ref<string | null>(null);
  
  const userStore = useUserStore();
  const commentBody = ref('');
  const comments = ref<Comment[]>([]);
  const commentsLoading = ref(true);
  const commentsError = ref<string | null>(null);

  const fetchArticleDetail = async () => {
    const articleId = route.params.id; // 从路由参数获取文章ID
    if (!articleId) {
      error.value = '文章ID缺失。';
      loading.value = false;
      return;
    }
  
    try {
      const response = await fetch(`/api/demo/getsingle?id=${articleId}&typeIndex=1`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (data) {
        article.value = data;
      } else {
        article.value = null; // 未找到文章
      }
    } catch (e: any) {
      error.value = '获取文章详情失败: ' + e.message;
      console.error('获取文章详情失败:', e);
    } finally {
      loading.value = false;
    }
  };

  const fetchComments = async () => {
    const articleId = route.params.id; // 获取当前文章的ID
    if (!articleId) {
      commentsError.value = '无法获取文章ID，无法加载评论。';
      commentsLoading.value = false;
      return;
    }

    try {
      const response = await fetch(`/api/demo/getallitems?typeIndex=4&replyType=文章&articleid=${articleId}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (Array.isArray(data)) {
        comments.value = data;
      } else {
        console.warn('API返回评论数据格式可能不符合预期:', data);
        comments.value = []; // 确保 comments 始终是数组
      }
    } catch (e: any) {
      commentsError.value = '获取评论失败: ' + e.message;
      console.error('获取评论失败:', e);
    } finally {
      commentsLoading.value = false;
    }
  };
  
  const formatTime = (timeString: string) => {
    if (!timeString) return '未知时间';
    try {
      const date = new Date(timeString);
      return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).replace(/\//g, '-');
    } catch (e) {
      return timeString;
    }
  };
  
  const goBack = () => {
    router.push('/articles');
  };
  
  const submitComment = async () => {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录才能发表评论！');
      router.push('/login');
      return;
    }

    if (!commentBody.value.trim()) {
      ElMessage.warning('评论内容不能为空！');
      return;
    }

    const articleId = route.params.id; // 获取当前文章的ID
    if (!articleId) {
      ElMessage.error('无法获取文章ID，无法提交评论。');
      return;
    }

    try {
      const response = await fetch('/api/demo/additem', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          articleid: parseInt(articleId as string), // 将文章ID转换为数字
          body: commentBody.value.trim(),
          userid: userStore.currentUserId, // 从 userStore 获取用户ID
          replyType: '文章',
          typeIndex: 4,
        }),
      });

      const result = await response.json();

      if (response.ok && result.id) { // 假设成功标志是 result 中包含 id 字段
        ElMessage.success('评论发表成功！');
        commentBody.value = ''; // 清空评论输入框
        fetchComments(); // 刷新评论列表
      } else {
        ElMessage.error('评论发表失败: ' + (result.message || '未知错误'));
      }
    } catch (e: any) {
      ElMessage.error('评论发表异常: ' + e.message);
      console.error('评论发表异常:', e);
    }
  };

  onMounted(() => {
    fetchArticleDetail();
    fetchComments(); // 在组件挂载时获取评论
  });
  </script>
  
  <style scoped>
  .article-detail-container {
    max-width: 850px; /* 稍微增加最大宽度 */
    margin: 40px auto; /* 调整上下边距 */
    padding: 35px; /* 增加内边距 */
    background-color: #ffffff;
    border-radius: 15px; /* 增加圆角 */
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1); /* 增强阴影效果 */
    font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif; /* 更新字体栈 */
    position: relative;
    overflow: hidden; /* 确保内容不溢出圆角 */
  }
  
  .back-button {
    position: absolute;
    top: 25px; /* 调整位置 */
    left: 25px; /* 调整位置 */
    background-color: #6c757d; /* 保持原有颜色 */
    border-color: #6c757d;
    padding: 8px 15px; /* 调整按钮内边距 */
    font-size: 0.95em; /* 调整字体大小 */
    border-radius: 8px; /* 增加按钮圆角 */
    transition: background-color 0.3s ease, border-color 0.3s ease, transform 0.2s ease; /* 添加过渡效果 */
  }
  
  .back-button:hover {
    background-color: #5a6268;
    border-color: #545b62;
    transform: translateY(-2px); /* 悬停时轻微上浮 */
  }
  
  .loading,
  .error,
  .no-article {
    text-align: center;
    font-size: 1.3em; /* 稍微增大字体 */
    color: #777; /* 调整颜色 */
    padding: 60px;
  }
  
  .error {
    color: #e74c3c; /* 使用更鲜艳的颜色 */
  }
  
  .article-title {
    text-align: center;
    color: #2c3e50; /* 使用更深的标题颜色 */
    margin-bottom: 25px; /* 调整间距 */
    font-size: 2.8em; /* 增大标题字体 */
    font-weight: 700;
    line-height: 1.2;
    padding-top: 50px; /* 为返回按钮留出更多空间 */
    word-break: break-word; /* 确保长标题能换行 */
  }
  
  .article-meta {
    font-size: 1em; /* 调整字体大小 */
    color: #888; /* 调整颜色 */
    margin-bottom: 35px; /* 调整间距 */
    text-align: center;
    display: flex;
    justify-content: center;
    gap: 25px; /* 增加间距 */
    flex-wrap: wrap;
  }
  
  .article-meta .author {
    font-weight: 600; /* 调整字重 */
    color: #555; /* 调整颜色 */
  }
  
  .article-body {
    margin-bottom: 40px; /* 增加间距 */
    line-height: 1.9; /* 增加行高 */
    font-size: 1.15em; /* 调整字体大小 */
    color: #34495e; /* 调整颜色 */
    white-space: pre-wrap;
    word-break: break-word; /* 确保长单词能换行 */
  }
  
  .article-body p {
    margin-bottom: 1.2em; /* 调整段落间距 */
  }
  
  .article-details {
    display: flex;
    flex-wrap: wrap;
    gap: 12px; /* 调整间距 */
    font-size: 0.9em;
    color: #7f8c8d; /* 调整颜色 */
    border-top: 1px solid #ecf0f1; /* 调整边框颜色 */
    padding-top: 20px;
    margin-top: 20px;
    justify-content: center;
  }
  
  .article-details .detail-item {
    background-color: #f0f4f7; /* 调整背景颜色 */
    padding: 7px 14px; /* 调整内边距 */
    border-radius: 6px; /* 调整圆角 */
    color: #555; /* 调整字体颜色 */
  }
  
  .comments-section {
    margin-top: 40px;
    padding-top: 30px;
    border-top: 1px solid #eee;
  }
  
  .comments-section h3 {
    font-size: 1.8em;
    color: #333;
    margin-bottom: 20px;
    text-align: center;
  }
  
  .comment-textarea {
    width: 100%;
    margin-bottom: 15px;
    border-radius: 8px;
    font-size: 1em;
  }
  
  .submit-comment-button {
    display: block;
    margin: 0 auto;
    padding: 10px 25px;
    font-size: 1.1em;
    border-radius: 8px;
    background-color: #007bff;
    border-color: #007bff;
    transition: background-color 0.3s ease, border-color 0.3s ease;
  }
  
  .submit-comment-button:hover {
    background-color: #0056b3;
    border-color: #0056b3;
  }
  
  .comments-list-title {
    font-size: 1.6em;
    color: #333;
    margin-top: 30px;
    margin-bottom: 20px;
    text-align: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }
  
  .comments-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .comment-card {
    background-color: #f9f9f9;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease-in-out;
  }
  
  .comment-card:hover {
    transform: translateY(-3px);
  }
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 0.95em;
    color: #666;
  }
  
  .comment-author {
    font-weight: bold;
    color: #007bff;
  }
  
  .comment-time {
    color: #999;
  }
  
  .comment-body {
    font-size: 1em;
    color: #444;
    line-height: 1.6;
    margin-bottom: 10px;
    white-space: pre-wrap;
    word-break: break-word;
  }
  
  .comment-index {
    font-size: 0.85em;
    color: #aaa;
    text-align: right;
    display: block;
    margin-top: 10px;
    border-top: 1px dashed #eee;
    padding-top: 5px;
  }
  
  .no-comments {
    text-align: center;
    font-size: 1.1em;
    color: #888;
    padding: 20px;
  }
  </style>